# utils/file_utils.py
import os
import json
from pathlib import Path

def ensure_directory_exists(path):
    """确保目录存在，如果不存在则创建"""
    if isinstance(path, str):
        path = Path(path)
    path.mkdir(parents=True, exist_ok=True)
    return path

def save_json(data, file_path):
    """保存数据到JSON文件"""
    if isinstance(file_path, str):
        file_path = Path(file_path)
    file_path.parent.mkdir(parents=True, exist_ok=True)
    with open(file_path, 'w', encoding='utf-8') as f:
        json.dump(data, f, indent=2, ensure_ascii=False)
    return file_path

def load_json(file_path):
    """从JSON文件加载数据"""
    if isinstance(file_path, str):
        file_path = Path(file_path)
    with open(file_path, 'r', encoding='utf-8') as f:
        return json.load(f)

def save_file(file_path, content):
    """保存内容到文件"""
    if isinstance(file_path, str):
        file_path = Path(file_path)
    file_path.parent.mkdir(parents=True, exist_ok=True)
    with open(file_path, 'w', encoding='utf-8') as f:
        f.write(content)
    return file_path

def read_file(file_path):
    """从文件读取内容"""
    if isinstance(file_path, str):
        file_path = Path(file_path)
    with open(file_path, 'r', encoding='utf-8') as f:
        return f.read()